import 'dart:collection';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/checkin/checkinmodel.dart';
import 'package:opene/utils/ImageUtils.dart';
import 'package:scan_gun/scan_gun.dart';
import 'package:toast/toast.dart';

import 'tallydialogscreen.dart';
import 'tallylpnscreen.dart';
import 'tallymodel.dart';

class TallySkuScreen extends StatelessWidget {
  TallyQr data;

  TallySkuScreen({this.data});

  @override
  Widget build(BuildContext context) {
    return TallySkuScreenPage(data: data);
  }
}

class TallySkuScreenPage extends StatefulWidget {
  TallyQr data;

  TallySkuScreenPage({this.data});

  @override
  _TallySkuScreenPageState createState() => _TallySkuScreenPageState(tallyQr: data);
}

class _TallySkuScreenPageState extends BaseState<TallySkuScreenPage> {
  TallyQr tallyQr;

  _TallySkuScreenPageState({this.tallyQr});

  final TextEditingController ctnEditingController = TextEditingController();
  final TextEditingController pcsEditingController = TextEditingController();
  bool layoutPcs = false;

  final TextEditingController lengthEditingController = TextEditingController();
  final TextEditingController widthEditingController = TextEditingController();
  final TextEditingController heightEditingController = TextEditingController();
  final TextEditingController weightEditingController = TextEditingController();

  int index = 0, position, ctn = 0, pcs = 0;

  final controller = ScrollController();

  List<TallyDetail> tallyDetails = new List();

  PhotoBean lengthPhoto = new PhotoBean();
  PhotoBean widthPhoto = new PhotoBean();
  PhotoBean heightPhoto = new PhotoBean();
  PhotoBean weightPhoto = new PhotoBean();
  List<PhotoBean> damages = new List();

  List<Tally> data = new List();
  List<Tally> dataAll = new List();

  @override
  String setTitle({String title}) {
    return tallyQr.type == "good" ? "Tally：Good-SKU" : "Tally：Damage-SKU";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    damages.add(new PhotoBean());

    // 特定事件监听
    eventBus.on<TallyQr>().listen((event) {
      print("event:${event.lengthPhoto}");
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => TallyLpnScreen(data: event)),
      ).then((value) => {Navigator.pop(context, value)});
    });

    textFiledNode.requestFocus();
  }

  @override
  void dispose() {
    textFiledNode.dispose(); // 不要忘记销毁FocusNode
    ctnFocusNode.dispose(); // 不要忘记销毁FocusNode
    pcsFocusNode.dispose(); // 不要忘记销毁FocusNode
    lengthFocusNode.dispose(); // 不要忘记销毁FocusNode
    widthFocusNode.dispose(); // 不要忘记销毁FocusNode
    heightFocusNode.dispose(); // 不要忘记销毁FocusNode
    weightFocusNode.dispose(); // 不要忘记销毁FocusNode
    super.dispose();
  }

  Future<void> setComplete() async {
    bool result = await showDialog(
      context: context,
      builder: (context) => CompleteDialog(id: tallyQr.notifyId),
    );
    if (result) {
      Navigator.pop(context, true);
    }
  }
  FocusNode textFiledNode = FocusNode();
  FocusNode ctnFocusNode = FocusNode();
  FocusNode pcsFocusNode = FocusNode();
  FocusNode lengthFocusNode = FocusNode();
  FocusNode widthFocusNode = FocusNode();
  FocusNode heightFocusNode = FocusNode();
  FocusNode weightFocusNode = FocusNode();


  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, top: 10, right: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(left: 15, right: 15),
            child: Row(
              children: [
                Text(
                  "Container NO#: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(
                    Utils.getStringisEmpty(tallyQr.container_no),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    getWarehousingDetailTallyInfo(tallyQr);
                  },
                  child: Container(
                    margin: EdgeInsets.only(left: 5, right: 10),
                    child: Image.asset(
                      'assets/images/details.png',
                      width: 20,
                      height: 20,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 2),
            child: Row(
              children: [
                Text(
                  "Uniq ID: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(
                    Utils.getStringisEmpty(tallyQr.inboundNo),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    // 请求焦点
                    FocusScope.of(context).requestFocus(FocusNode());
                    setComplete();
                  },
                  child: Container(
                    padding: EdgeInsets.only(left: 5, top: 2, bottom: 2, right: 5),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: MyAppTheme.white, // 背景颜色
                      borderRadius: BorderRadius.all(Radius.circular(8.0)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'Complete',
                      style: MyAppTheme.text,
                    ), // 子控件，如果需要的话
                  ),
                )
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 10, left: 15, right: 15),
            child: Row(
              children: [
                Expanded(
                  flex: 1, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      if (type == 1) {
                        return;
                      }
                      setState(() {
                        type = 1;
                        textEditingController.text = "";
                        data.clear();
                        tallyQr.type = "good";
                        setTitle();
                        reset();
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(5),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                        borderRadius: BorderRadius.only(topLeft: Radius.circular(8.0), bottomLeft: Radius.circular(8.0)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        'Good',
                        style: type == 1 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                      ), // 子控件，如果需要的话
                    ),
                  ),
                ),
                Expanded(
                  flex: 1, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      if (type == 2) {
                        return;
                      }
                      setState(() {
                        type = 2;
                        textEditingController.text = "";
                        data.clear();
                        tallyQr.type = "damage";
                        setTitle();
                        reset();
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(5),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                        borderRadius: BorderRadius.only(topRight: Radius.circular(8.0), bottomRight: Radius.circular(8.0)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        'Damage',
                        style: type == 2 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                      ), // 子控件，如果需要的话
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                focusNode: textFiledNode,
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                  getTallySkuBase(text);
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                        getTallySkuBase(text);
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "product barcode or sku",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Visibility(
              child: Container(
            margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
            child: Row(
              children: [
                Container(
                  width: 60,
                  child: Text(
                    "Cartons: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                ),
                Expanded(
                  child: ConstrainedBox(
                    constraints: BoxConstraints(maxHeight: 35),
                    child: TextField(
                      maxLines: 1,
                      focusNode: ctnFocusNode,
                      controller: ctnEditingController,
                      keyboardType: TextInputType.number,
                      textInputAction: TextInputAction.next,
                      onSubmitted: (String text) {
                        if(layoutPcs){
                          pcsFocusNode.requestFocus();
                        }else{
                          lengthFocusNode.requestFocus();
                        }
                      },
                      // autofocus: true,
                      decoration: InputDecoration(
                        suffixIcon: IconButton(
                          padding: EdgeInsets.all(2.0),
                          icon: Icon(
                            Icons.remove_circle_outline,
                            size: 30,
                            color: MyAppTheme.nearlyBlue,
                          ),
                          onPressed: () {
                            setState(() {
                              print("ctnonPressed");
                              if (ctn == 0) {
                                return;
                              }
                              ctn--;
                              ctnEditingController.text = "${ctn}";
                            });
                          },
                        ),
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: MyAppTheme.nearlyBlue,
                          ),
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                          // 设置焦点之外的边框颜色
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                          // 设置焦点时的边框颜色
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        hintText: "Scan +1",
                        filled: true,
                        fillColor: MyAppTheme.white,
                        //隐藏下划线
                        //border: InputBorder.none,
                        hintStyle: TextStyle(color: Colors.grey),
                        contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                      ),
                      onChanged: (text) {
                        print("ctn:${text}");
                        print("code:${code}");
                        if (Utils.isEmpty(code)) {
                          ctnEditingController.text = "";
                          return;
                        }
                        if (tallySkuBase == null) {
                          ctnEditingController.text = "";
                          return;
                        }
                        if (Utils.isEmpty(text)) {
                          return;
                        }
                        if (text == code) {
                          ctn++;
                          ctnEditingController.text = "${ctn}";
                          Future.delayed(Duration(milliseconds: 100), () {
                            setState(() {
                              ctnFocusNode.requestFocus();
                            });
                          });
                          return;
                        }
                        if (text == "${ctn}${code}") {
                          ctn++;
                          ctnEditingController.text = "${ctn}";
                          Future.delayed(Duration(milliseconds: 100), () {
                            setState(() {
                              ctnFocusNode.requestFocus();
                            });
                          });
                          return;
                        }

                        List<String> barcodes = tallySkuBase.barcodes;
                        barcodes.forEach((value) {
                          if ((!Utils.isEmpty(value)) && (value == code)) {
                            ctn++;
                            ctnEditingController.text = "${ctn}";
                            Future.delayed(Duration(milliseconds: 100), () {
                              setState(() {
                                ctnFocusNode.requestFocus();
                              });
                            });
                            return;
                          }

                          if ((!Utils.isEmpty(value)) && (value == "${ctn}${code}")) {
                            ctn++;
                            ctnEditingController.text = "${ctn}";
                            Future.delayed(Duration(milliseconds: 100), () {
                              setState(() {
                                ctnFocusNode.requestFocus();
                              });
                            });
                            return;
                          }
                        });

                        if (!Utils.isInteger(text)) {
                          ctnEditingController.text = "${ctn}";
                          return;
                        }

                        if (int.parse(text) < 0) {
                          ctnEditingController.text = "${ctn}";
                          return;
                        }else{
                          ctn = int.parse(text);
                        }
                      },
                    ),
                  ),
                ),
              ],
            ),
          )),
          Visibility(
              visible: layoutPcs,
              child: Container(
                margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
                child: Row(
                  children: [
                    Container(
                      width: 60,
                      child: Text(
                        "PCS: ",
                        style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                      ),
                    ),
                    Expanded(
                        child: ConstrainedBox(
                      constraints: BoxConstraints(maxHeight: 35),
                      child: TextField(
                        focusNode: pcsFocusNode,
                        controller: pcsEditingController,
                        keyboardType: TextInputType.number,
                        textInputAction: TextInputAction.next,
                        onSubmitted: (String text) {
                            lengthFocusNode.requestFocus();
                        },
                        // autofocus: true,
                        decoration: InputDecoration(
                          suffixIcon: IconButton(
                            padding: EdgeInsets.all(2.0),
                            icon: Icon(
                              Icons.remove_circle_outline,
                              size: 30,
                              color: MyAppTheme.nearlyBlue,
                            ),
                            onPressed: () {
                              setState(() {
                                if (pcs == 0) {
                                  return;
                                }
                                pcs--;
                                pcsEditingController.text = "${pcs}";
                              });
                            },
                          ),
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: MyAppTheme.nearlyBlue,
                            ),
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点之外的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点时的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          hintText: "Scan +1",
                          filled: true,
                          fillColor: MyAppTheme.white,
                          //隐藏下划线
                          //border: InputBorder.none,
                          hintStyle: TextStyle(color: Colors.grey),
                          contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                        ),
                        onChanged: (text) {
                          if (Utils.isEmpty(code)) {
                            pcsEditingController.text = "";
                            return;
                          }
                          if (tallySkuBase == null) {
                            pcsEditingController.text = "";
                            return;
                          }
                          if (Utils.isEmpty(text)) {
                            return;
                          }
                          if (text == code) {
                            pcs++;
                            pcsEditingController.text = "${pcs}";
                            Future.delayed(Duration(milliseconds: 100), () {
                              setState(() {
                                pcsFocusNode.requestFocus();
                              });
                            });
                            return;
                          }
                          if (text == "${pcs}${code}") {
                            pcs++;
                            pcsEditingController.text = "${pcs}";
                            Future.delayed(Duration(milliseconds: 100), () {
                              setState(() {
                                pcsFocusNode.requestFocus();
                              });
                            });
                            return;
                          }

                          List<String> barcodes = tallySkuBase.barcodes;
                          barcodes.forEach((value) {
                            if ((!Utils.isEmpty(value)) && (value == code)) {
                              pcs++;
                              pcsEditingController.text = "${pcs}";
                              Future.delayed(Duration(milliseconds: 100), () {
                                setState(() {
                                  pcsFocusNode.requestFocus();
                                });
                              });
                              return;
                            }

                            if ((!Utils.isEmpty(value)) && (value == "${pcs}${code}")) {
                              pcs++;
                              pcsEditingController.text = "${pcs}";
                              Future.delayed(Duration(milliseconds: 100), () {
                                setState(() {
                                  pcsFocusNode.requestFocus();
                                });
                              });
                              return;
                            }
                          });

                          if (!Utils.isInteger(text)) {
                            pcsEditingController.text = "${pcs}";
                            return;
                          }

                          if (int.parse(text) < 0) {
                            pcsEditingController.text = "${pcs}";
                            return;
                          }else{
                            pcs = int.parse(text);
                          }
                        },
                      ),
                    )),
                  ],
                ),
              )),
          Expanded(
            flex: 1, //设置权重
            child: SingleChildScrollView(
              controller: controller, // 设置控制器
              child: Column(
                children: [
                  Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: setPhotoView("length:  ", 0, lengthPhoto, "inch", lengthEditingController,lengthFocusNode),
                      ),
                      Expanded(
                        flex: 1,
                        child: setPhotoView("width:  ", 1, widthPhoto, "inch", widthEditingController,widthFocusNode),
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: setPhotoView("height:  ", 2, heightPhoto, "inch", heightEditingController,heightFocusNode),
                      ),
                      Expanded(
                        flex: 1,
                        child: setPhotoView("weight:  ", 3, weightPhoto, "lb", weightEditingController,weightFocusNode),
                      ),
                    ],
                  ),
                  Visibility(
                    visible: type == 2 ? true : false,
                    child: Container(
                      margin: const EdgeInsets.only(left: 15, top: 10, right: 0, bottom: 0),
                      child: Column(
                        children: <Widget>[
                          Row(
                            children: [
                              Text(
                                '*',
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                              ),
                              Text(
                                'Damage(s):',
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 5,
                          ),
                          Container(
                            height: 70,
                            width: double.infinity,
                            child: setPhotoListView(4, damages),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Container setPhotoView(String hintText, int type, PhotoBean photoBean, String hint, TextEditingController editingController,FocusNode focusNode) {
    return Container(
      margin: const EdgeInsets.only(left: 0, top: 10, right: 0, bottom: 0),
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Expanded(
            flex: 1, //设置权重
            child: Container(
              margin: EdgeInsets.only(top: 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Text(
                    '*',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                  ),
                  Text(
                    hintText,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
              flex: 2, //设置权重
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: 70,
                    child: ConstrainedBox(
                      constraints: BoxConstraints(maxHeight: 30),
                      child: TextField(
                        focusNode: focusNode,
                        keyboardType: TextInputType.number,
                        controller: editingController,
                        textInputAction: TextInputAction.next,
                        // autofocus: true,
                        decoration: InputDecoration(
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: MyAppTheme.nearlyBlue,
                            ),
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点之外的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点时的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          hintText: hint,
                          filled: true,
                          fillColor: MyAppTheme.white,
                          //隐藏下划线
                          //border: InputBorder.none,
                          hintStyle: const TextStyle(color: Colors.grey),
                          contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                        ),
                        onChanged: (text) {
                          if (!Utils.isDouble(text)) {
                            editingController.text = "";
                            return;
                          }
                        },
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 5,
                  ),
                  Row(
                    children: [
                      Container(
                        width: 70,
                        height: 70,
                        child: Stack(
                          children: <Widget>[
                            GestureDetector(
                              onTap: () {
                                // 请求焦点
                                FocusScope.of(context).requestFocus(FocusNode());
                                index = type;
                                ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? pickImages(context) : imgFileDialog(photoBean, Constants.baseImgUrl);
                              },
                              child: photoBean.image == null
                                  ? (photoBean.urlImg == null
                                      ? Image.asset(
                                          'assets/images/add.png',
                                          width: 70,
                                          height: 70,
                                          fit: BoxFit.cover,
                                        )
                                      : Image.network(
                                          Constants.baseImgUrl + photoBean.urlImg,
                                          width: 70,
                                          height: 70,
                                          fit: BoxFit.cover,
                                        ))
                                  : Image.file(
                                      photoBean.image,
                                      width: 70,
                                      height: 70,
                                      fit: BoxFit.cover,
                                    ),
                            ),
                            Visibility(
                              visible: ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? false : true,
                              child: Positioned(
                                top: 2.0,
                                right: 2.0,
                                child: GestureDetector(
                                  onTap: () {
                                    setState(() {
                                      photoBean.urlImg = null;
                                      photoBean.image = null;
                                    });
                                  },
                                  child: Image.asset(
                                    'assets/images/ic_delete_menu.png',
                                    width: 15,
                                    height: 15,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        flex: 2, //设置权重
                        child: Text(
                          '',
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                        ),
                      ),
                    ],
                  ),
                ],
              )),
        ],
      ),
    );
  }

  ListView setPhotoListView(int type, List<PhotoBean> data) {
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        PhotoBean photoBean = data[index];
        print(photoBean.toString());
        return Container(
          height: 70,
          width: 70,
          margin: const EdgeInsets.only(left: 0, top: 0, right: 10, bottom: 0),
          child: Stack(
            children: <Widget>[
              GestureDetector(
                onTap: () {
                  // 请求焦点
                  FocusScope.of(context).requestFocus(FocusNode());
                  this.index = type;
                  this.position = index;
                  ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? pickImages(context) : imgFileDialog(photoBean, Constants.baseImgUrl);
                },
                child: photoBean.image == null
                    ? (photoBean.urlImg == null
                        ? Image.asset(
                            'assets/images/add.png',
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          )
                        : Image.network(
                            Constants.baseImgUrl + photoBean.urlImg,
                            width: 70,
                            height: 70,
                            fit: BoxFit.cover,
                          ))
                    : Image.file(
                        photoBean.image,
                        width: 70,
                        height: 70,
                        fit: BoxFit.cover,
                      ),
              ),
              Visibility(
                visible: ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? false : true,
                child: Positioned(
                  top: 2.0,
                  left: 53,
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        data.removeAt(index);
                      });
                    },
                    child: Image.asset(
                      'assets/images/ic_delete_menu.png',
                      width: 15,
                      height: 15,
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Future pickImages(context) async {
    File image = await ImageUtils.chosePhotoOnAlbumOrCamera(context: context);
    print(image.path);
    String name = "";
    setState(() {
      switch (index) {
        case 0:
          lengthPhoto.image = image;
          name = "length";
          break;
        case 1:
          widthPhoto.image = image;
          name = "width";
          break;
        case 2:
          heightPhoto.image = image;
          name = "height";
          break;
        case 3:
          weightPhoto.image = image;
          name = "weight";
          break;
        case 4:
          PhotoBean photoBean = new PhotoBean();
          photoBean.image = image;
          damages.insert(position, photoBean);
          name = "damage";
          break;
      }
      fileUpload(tallyQr.container_no, "tally", image, name, index, position, false, false);
      print("index:${index},position:${position}");
      print(image.path);
    });
  }

  @override
  void setNext() {
    ToastContext().init(context);
    if (Utils.isEmpty(code)) {
      Toast.show("Please enter the SKU/Barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (tallySkuBase == null) {
      getTallySkuBase(code);
    }
    setSubmit();
  }

  void setSubmit() {
    ToastContext().init(context);
    if (Utils.isEmpty(tallySkuBase.upType)) {
      if (ctn < 1) {
        Toast.show("please input cartons", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      if (tallySkuBase != null) {
        tallyQr.warehousingDetailId = tallySkuBase.warehousingDetailId;
        tallyQr.upType = tallySkuBase.upType;
      }
      tallyQr.ctnQty = ctn;
      tallyQr.pcsQty = 0;
      tallyQr.quantity = ctn;
    } else if (tallySkuBase.upType == "CTN") {
      if (ctn < 1) {
        Toast.show("please input cartons", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      tallyQr.warehousingDetailId = tallySkuBase.warehousingDetailId;
      tallyQr.upType = tallySkuBase.upType;
      tallyQr.ctnQty = ctn;
      tallyQr.pcsQty = 0;
      tallyQr.quantity = ctn;
    } else if (tallySkuBase.upType == "PCS") {
      if (ctn < 1) {
        Toast.show("please input cartons", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      if (pcs < 1) {
        Toast.show("please input pcs", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      if (ctn > pcs) {
        Toast.show("PCS need be equal or greater than CTN", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }

      tallyQr.warehousingDetailId = tallySkuBase.warehousingDetailId;
      tallyQr.upType = tallySkuBase.upType;
      tallyQr.ctnQty = ctn;
      tallyQr.pcsQty = pcs;
      tallyQr.quantity = pcs;
    }
    if (DateTime.now().millisecondsSinceEpoch - timeMillis < 1000) {
      return;
    }
    timeMillis = DateTime.now().millisecondsSinceEpoch;

    if (tallySkuBase.isShowSkuBase || (type == 2)) {
      //是否回显sku尺寸
      String length = lengthEditingController.text;
      if (!judgeType(length, "Please enter the length")) {
        return;
      }
      String width = widthEditingController.text;
      if (!judgeType(width, "Please enter the width")) {
        return;
      }
      String height = heightEditingController.text;
      if (!judgeType(height, "Please enter the height")) {
        return;
      }
      String weight = weightEditingController.text;
      if (!judgeType(weight, "Please enter the weight")) {
        return;
      }
      if ((lengthPhoto.image == null) && (lengthPhoto.urlImg == null)) {
        Toast.show("Please add length photo", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      if ((widthPhoto.image == null) && (widthPhoto.urlImg == null)) {
        Toast.show("Please add width photo", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      if ((heightPhoto.image == null) && (heightPhoto.urlImg == null)) {
        Toast.show("Please add height photo", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      if ((weightPhoto.image == null) && (weightPhoto.urlImg == null)) {
        Toast.show("Please add weight photo", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }

      if (Utils.isEmpty(lengthPhoto.urlImg)) {
        fileUpload(tallyQr.container_no, "tally", lengthPhoto.image, "length", 0, position, true, true);
        return;
      }
      if (Utils.isEmpty(widthPhoto.urlImg)) {
        fileUpload(tallyQr.container_no, "tally", widthPhoto.image, "width", 1, position, true, true);
        return;
      }
      if (Utils.isEmpty(heightPhoto.urlImg)) {
        fileUpload(tallyQr.container_no, "tally", heightPhoto.image, "height", 2, position, true, true);
        return;
      }
      if (Utils.isEmpty(weightPhoto.urlImg)) {
        fileUpload(tallyQr.container_no, "tally", weightPhoto.image, "height", 3, position, true, true);
        return;
      }
      tallyQr.weight = double.parse(weightEditingController.text);
      tallyQr.weightPhoto = weightPhoto.urlImg;
      tallyQr.length = double.parse(lengthEditingController.text);
      tallyQr.lengthPhoto = lengthPhoto.urlImg;
      tallyQr.width = double.parse(widthEditingController.text);
      tallyQr.widthPhoto = widthPhoto.urlImg;
      tallyQr.height = double.parse(heightEditingController.text);
      tallyQr.heightPhoto = heightPhoto.urlImg;
    } else {
      SkuBaseRespVoDTO skuBaseRespVo = tallySkuBase.skuBaseRespVo;
      if (skuBaseRespVo != null) {
        tallyQr.weight = skuBaseRespVo.weight;
        tallyQr.weightPhoto = skuBaseRespVo.weightPhoto;
        tallyQr.length = skuBaseRespVo.length;
        tallyQr.lengthPhoto = skuBaseRespVo.lengthPhoto;
        tallyQr.width = skuBaseRespVo.width;
        tallyQr.widthPhoto = skuBaseRespVo.widthPhoto;
        tallyQr.height = skuBaseRespVo.height;
        tallyQr.heightPhoto = skuBaseRespVo.heightPhoto;
      }
    }

    if (type == 2) {
      if (damages.length == 0) {
        Toast.show("Please add damaged photos", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      List<String> damagesTemp = new List();
      for (int i = 0; i < damages.length - 1; i++) {
        PhotoBean photoBean = damages[i];
        if (Utils.isEmpty(photoBean.urlImg)) {
          position = i;
          fileUpload(tallyQr.container_no, "tally", photoBean.image, "damage", 4, position, true, true);
          return;
        }
        damagesTemp.add(photoBean.urlImg);
      }
      tallyQr.damagePhotos = damagesTemp;
    }

    tallyQr.sku_barcode = code;
    tallyQr.sku = code;

    if (!tallySkuBase.isShowSkuBase) {
      //是否回显sku尺寸
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => TallyLpnScreen(data: tallyQr)),
      ).then((value) => {Navigator.pop(context, value)});
      return;
    }
    List<double> sizes = new List();
    sizes.add(tallyQr.length);
    sizes.add(tallyQr.width);
    sizes.add(tallyQr.height);
    CheckSkuParam checkSkuParam = new CheckSkuParam();
    checkSkuParam.warehousingNotifyId =tallyQr.warehousingDetailId;
    checkSkuParam.sku =code;
    checkSkuParam.weight =tallyQr.weight;
    checkSkuParam.smallItem = tallySkuBase.skuBaseRespVo == null ? false : tallySkuBase.skuBaseRespVo.smallItem;
    checkSku(checkSkuParam, tallyQr);
  }

  bool judgeType(String mold, String hint) {
    if (Utils.isEmpty(mold)) {
      Toast.show(hint, duration: Toast.lengthShort, gravity: Toast.bottom);
      return false;
    }

    if (double.parse(mold) <= 0) {
      Toast.show(hint, duration: Toast.lengthShort, gravity: Toast.bottom);
      return false;
    }
    return true;
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
    reset();
  }

  void reset() {
    setState(() {
      tallySkuBase = null;
      ctn = 0;
      pcs = 0;
      layoutPcs = false;
      lengthPhoto = new PhotoBean();
      widthPhoto = new PhotoBean();
      heightPhoto = new PhotoBean();
      weightPhoto = new PhotoBean();
      damages = new List();
      damages.add(new PhotoBean());
      ctnEditingController.text = "";
      pcsEditingController.text = "";
      lengthEditingController.text = "";
      widthEditingController.text = "";
      heightEditingController.text = "";
      weightEditingController.text = "";
    });
  }

  TallySkuBase tallySkuBase;

  void getTallySkuBase(String sku) async {
    reset();

    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    Map<String, dynamic> map = new HashMap();
    map["barcodeSku"] = sku;
    if (tallyQr.notifyId > 0) {
      map["warehousingNotifyId"] = tallyQr.notifyId;
    }
    if (tallyQr.type == 1) {
      map["type"] = "good";
    } else {
      map["type"] = "damage";
    }

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.tallySkuBase, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        tallySkuBase = TallySkuBase.fromJson(baseResponse.data);

        if (tallySkuBase == null) {
          return;
        }

        var skuBaseRespVo = tallySkuBase.skuBaseRespVo;
        if (skuBaseRespVo == null) {
          return;
        }
        ctnFocusNode.requestFocus();

        if (!Utils.isEmpty(skuBaseRespVo.lengthPhoto)) {
          lengthPhoto.urlImg = skuBaseRespVo.lengthPhoto;
        }
        if (!Utils.isEmpty(skuBaseRespVo.widthPhoto)) {
          widthPhoto.urlImg = skuBaseRespVo.lengthPhoto;
        }
        if (!Utils.isEmpty(skuBaseRespVo.heightPhoto)) {
          heightPhoto.urlImg = skuBaseRespVo.lengthPhoto;
        }
        if (!Utils.isEmpty(skuBaseRespVo.weightPhoto)) {
          weightPhoto.urlImg = skuBaseRespVo.lengthPhoto;
        }

        if ((skuBaseRespVo.length != null) && (skuBaseRespVo.length > 0)) {
          lengthEditingController.text = "${skuBaseRespVo.length}";
        }
        if ((skuBaseRespVo.width != null) && (skuBaseRespVo.width > 0)) {
          widthEditingController.text = "${skuBaseRespVo.width}";
        }
        if ((skuBaseRespVo.height != null) && (skuBaseRespVo.height > 0)) {
          heightEditingController.text = "${skuBaseRespVo.height}";
        }
        if ((skuBaseRespVo.weight != null) && (skuBaseRespVo.weight > 0)) {
          weightEditingController.text = "${skuBaseRespVo.weight}";
        }
        if (Utils.isEmpty(tallySkuBase.upType)) {
          return;
        }
        if (tallySkuBase.upType == 'PCS') {
          layoutPcs = true;
          return;
        }
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void checkSku(CheckSkuParam checkSkuParam, TallyQr tallyQr) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    String json = jsonEncode(checkSkuParam);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.checkSkuParam, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        CheckSkuParam checkSkuParamTemp = CheckSkuParam.fromJson(baseResponse.data);
        double weight = checkSkuParamTemp.weight;
        List<double> sizes = checkSkuParamTemp.sizes;
        bool isLength = false;
        bool isWidth = false;
        bool isHeight = false;
        bool isWeight = false;

        if (weight != null) {
          isWeight = true;
        }
        sizes.forEach((d) {
          if (d - tallyQr.length == 0) {
            //
            isLength = true;
          }
          if (d - tallyQr.width == 0) {
            //
            isWidth = true;
          }
          if (d - tallyQr.height == 0) {
            //
            isHeight = true;
          }
        });

        // getView().showCheckSkuParam(isLength, isWidth, isHeight, isWeight);

        if ((!isLength) && (!isWidth) && (!isHeight) && (!isWeight)) {
          if (checkSkuParamTemp.smallItem == null) {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => TallyLpnScreen(data: tallyQr)),
            ).then((value) => {Navigator.pop(context, value)});
            return;
          }
          showDialog(
            context: context,
            builder: (context) => CheckSkuDialog(tally: tallyQr, smallItem: checkSkuParamTemp.smallItem),
          ).then((value) => {
                print("result:${value}"),
                if ((value != null) && (value == "ok"))
                  {
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => TallyLpnScreen(data: tallyQr)),
                    ).then((value) => {Navigator.pop(context, value)})
                  }
              });

          return;
        }

        SkuExceed skuExceed = new SkuExceed();
        skuExceed.smallItem = checkSkuParamTemp.smallItem;
        skuExceed.isLength = isLength;
        skuExceed.isWidth = isWidth;
        skuExceed.isHeight = isHeight;
        skuExceed.isWeight = isWeight;
        showDialog(
          context: context,
          builder: (context) => SkuExceedDialog(skuExceed: skuExceed),
        ).then((value) => {
              print("result2:${value}"),
              if ((value != null) && (value == "ok"))
                {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => TallyLpnScreen(data: tallyQr)),
                  ).then((value) => {Navigator.pop(context, value)})
                }
            });
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    switch (type) {
      case 0:
        lengthPhoto.urlImg = path;
        break;
      case 1:
        widthPhoto.urlImg = path;
        break;
      case 2:
        heightPhoto.urlImg = path;
        break;
      case 3:
        weightPhoto.urlImg = path;
        break;
      case 4:
        damages[position].urlImg = path;
        break;
    }

    if (isSubmit) {
      setSubmit();
    }
  }

  void getWarehousingDetailTallyInfo(TallyQr tally) async {
    String url = Constants.getTallyDetail;
    if (tally.isFinish == 2) {
      url = Constants.getTallyFinishDetail;
    }

    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }

    Map<String, dynamic> map = new HashMap();
    map["warehousingNotifyId"] = tally.notifyId;
    BaseResponse baseResponse = await NetworkManager().request(context, url, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      tallyDetails = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => TallyDetail.fromJson(userJson)).toList());
      String result = await showDialog(
        context: context,
        builder: (context) => CustomDialog(tally: tally, tallyDetails: tallyDetails),
      );
      if (Utils.getStringisEmpty(result) == "ok") {}
      print("result:${result}");
      // setState(() {
      //   tallyDetails = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => TallyDetail.fromJson(userJson)).toList());
      //   showDialog(
      //     context: context,
      //     builder: (context) => CustomDialog(tally: tally, tallyDetails: tallyDetails),
      //   );
      // });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
}
